package com.myblog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myblog.mapper.SysRoleMapper;
import com.myblog.model.po.SysRole;
import com.myblog.model.po.SysUser;
import com.myblog.mapper.SysUserMapper;
import com.myblog.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author
 * @since 2022-08-29
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private static final String DEFAULT_PASSWORD = "$2a$10$rDkPvvAFV8kqwvKJzwlRv.i.q.wz1w1pz0SFsHn/55jNeZFQv/eCm";

    @Autowired
    private SysRoleMapper sysRoleMapper;


    @Override
    public Boolean deleteByUserId(Long userId) {
        SysUser sysUser = baseMapper.selectById(userId);
        sysUser.setIsEnabled(false);
        sysUser.setUpdateDate(LocalDateTime.now());
        baseMapper.updateById(sysUser);
        return true;
    }

    @Override
    public boolean saveOrUpdate(SysUser entity) {
        if(entity.getId()==null){
            entity.setPassword(DEFAULT_PASSWORD);
        }
        boolean flag = super.saveOrUpdate(entity);
        if (flag) {
            //先删除
            baseMapper.deleteUserRoleByUserId(entity.getId());
            if (!CollectionUtils.isEmpty(entity.getRoleIds())) {
                baseMapper.saveUserRole(entity.getId(), entity.getRoleIds());
            }
        }
        return super.saveOrUpdate(entity);
    }

    @Override
    public SysUser findById(Long id) {
        if (id == null) {
            return new SysUser();
        }
        SysUser sysUser = baseMapper.selectById(id);
        List<SysRole> roleList = sysRoleMapper.findByUserId(id);
        sysUser.setRoleList(roleList);
        sysUser.setRoleIds(sysUser.getRoleList());
        return sysUser;
    }

    @Override
    public IPage<SysUser> selectPage(Page<SysUser> page, SysUser sysUser) {
        return baseMapper.selectPage(page, sysUser);
    }

    @Override
    public SysUser findByMobile(String mobile) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        return getBaseMapper().selectOne(queryWrapper);
    }


}
